//
//  SignInWidget.swift
//  SignInWidget
//
//  Created by 王麒皓 on 2023/7/18.
//

import AppIntents

struct SignInWidget: AppIntent {
    static var title: LocalizedStringResource = "签到"
    
    
    func perform() async throws -> some IntentResult {
        self.signRecentEvent()
        return .result()
    }
    
    private func signRecentEvent() {
        // Download online data
        let classData = ClassNameData()
        var allClasses: [EventWithClassName] = []
        let date = Date()
        _ = classData.downloadDataByHttp {
            for _class in classData.ClassName {
                let classroom = CoreData(classNameStr: _class.name)
                classroom.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                _ = classroom.downloadDataByHttp {
                    for _event in classroom.events {
                        if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") && _event.state == -1 {
                            allClasses.append(EventWithClassName(_event: _event, name: _class.name, classType: classroom.classes[_event._class].name))
                        }
                    }
                }
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                if allClasses.count != 0 {
                    let sortedClass = allClasses.sorted(by: {return $0._event.start < $1._event.start})
                    var _class: EventWithClassName? = nil
                    for __class in sortedClass {
                        let remaining = Int((__class._event.start-date.timeIntervalSince1970)/60)
                        if remaining >= 0 {
                            _class = __class
                            break
                        }
                    }
                    if let _class = _class {
                        // MARK: Do Sign In check here
                        let classroom = CoreData(classNameStr: _class.name)
                        _ = classroom.downloadDataByHttp(completion: {
                            for idx in 0..<classroom.events.count {
                                if classroom.events[idx].start == _class._event.start {
                                    classroom.changeeventState(at: idx, to: .succeded)
                                    break
                                }
                            }
                        })
                        
                    }
                }
                print(classData, allClasses)
            }
        }
//        return classData.ClassName[0].name
    }
}
